﻿using Common.Models;
using Core.Entities.EC;
using Core.Entities.SM;
using Core.Interfaces;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Services.EC
{
    /// <summary>
    /// 能源信息服务
    /// </summary>
    public class EnergyService : BaseService<Energy, string>
    {
        private readonly IDapperRepository _dapperRepository;
        public EnergyService(
            IBaseRepository<Energy, string> repository,
            IPagedRepository<Energy, string> pagedRepository,
            IDapperRepository dapperRepository)
            : base(repository, pagedRepository)
        {
            _dapperRepository = dapperRepository;
        }

        /// <summary>
        /// 根据设备名称查询能源信息
        /// </summary>
        /// <param name="devName">设备名称</param>
        /// <returns>能源信息列表</returns>
        public async Task<IEnumerable<Energy>> GetByDevNameAsync(string devName)
        {
            var filter = new QueryFilter
            {
                Conditions = new List<FilterCondition>
                {
                    new FilterCondition { Field = "DevName", Operator = "=", Value = devName }
                }
            };

            var result = await _pagedRepository.GetPagedAsync(filter);
            return result.Data;
        }

        /// <summary>
        /// 根据工厂名称查询能源信息
        /// </summary>
        /// <param name="factoryName">工厂名称</param>
        /// <returns>能源信息列表</returns>
        public async Task<IEnumerable<Energy>> GetByFactoryNameAsync(string factoryName)
        {
            var filter = new QueryFilter
            {
                Conditions = new List<FilterCondition>
                {
                    new FilterCondition { Field = "FactoryName", Operator = "=", Value = factoryName }
                }
            };

            var result = await _pagedRepository.GetPagedAsync(filter);
            return result.Data;
        }

        /// <summary>
        /// 根据车间名称查询能源信息
        /// </summary>
        /// <param name="workshop">车间名称</param>
        /// <returns>能源信息列表</returns>
        public async Task<IEnumerable<Energy>> GetByWorkshopAsync(string workshop)
        {
            var filter = new QueryFilter
            {
                Conditions = new List<FilterCondition>
                {
                    new FilterCondition { Field = "Workshop", Operator = "=", Value = workshop }
                }
            };

            var result = await _pagedRepository.GetPagedAsync(filter);
            return result.Data;
        }

        /// <summary>
        /// 根据物质类型查询能源信息
        /// </summary>
        /// <param name="substance">物质类型</param>
        /// <returns>能源信息列表</returns>
        public async Task<IEnumerable<Energy>> GetBySubstanceAsync(string substance)
        {
            var filter = new QueryFilter
            {
                Conditions = new List<FilterCondition>
                {
                    new FilterCondition { Field = "Substance", Operator = "=", Value = substance }
                }
            };

            var result = await _pagedRepository.GetPagedAsync(filter);
            return result.Data;
        }

        /// <summary>
        /// 根据时间段查询能源信息
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>能源信息列表</returns>
        public async Task<IEnumerable<Energy>> GetByTimeRangeAsync(DateTime startTime, DateTime endTime)
        {
            var filter = new QueryFilter
            {
                Conditions = new List<FilterCondition>
                {
                    new FilterCondition { Field = "CreateTime", Operator = ">=", Value = startTime },
                    new FilterCondition { Field = "CreateTime", Operator = "<=", Value = endTime }
                }
            };

            var result = await _pagedRepository.GetPagedAsync(filter);
            return result.Data;
        }

        /// <summary>
        /// 获取指定物质的能耗统计
        /// </summary>
        /// <param name="substance">物质类型</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>总能耗量</returns>
        public async Task<decimal?> GetTotalEnergyConsumptionAsync(string substance, DateTime startTime, DateTime endTime)
        {
            var filter = new QueryFilter
            {
                Conditions = new List<FilterCondition>
                {
                    new FilterCondition { Field = "Substance", Operator = "=", Value = substance },
                    new FilterCondition { Field = "CreateTime", Operator = ">=", Value = startTime },
                    new FilterCondition { Field = "CreateTime", Operator = "<=", Value = endTime }
                }
            };

            var result = await _pagedRepository.GetPagedAsync(filter);

            if (result?.Data?.Any() == true)
            {
                return result.Data.Sum(e => e.EnergyConsumption);
            }

            return 0;
        }

        public class EnergyQueryDto
        {
            public QueryFilter Filter { get; set; }
            public Energy Energy { get; set; }
        }
        public void Query(QueryFilter filter, Energy energy)
        {
            filter.Conditions = filter.Conditions ?? new List<FilterCondition>();

            // 添加设备名称查询条件（精确匹配）
            if (!string.IsNullOrEmpty(energy.DevName))
            {
                filter.Conditions.Add(new FilterCondition
                {
                    Field = "DevName",
                    Operator = "like",
                    Value = energy.DevName
                });
            }

            // 添加工厂名称查询条件（精确匹配）
            if (!string.IsNullOrEmpty(energy.FactoryName))
            {
                filter.Conditions.Add(new FilterCondition
                {
                    Field = "FactoryName",
                    Operator = "like",
                    Value = energy.FactoryName
                });
            }

            // 添加车间名称查询条件（精确匹配）
            if (!string.IsNullOrEmpty(energy.Workshop))
            {
                filter.Conditions.Add(new FilterCondition
                {
                    Field = "Workshop",
                    Operator = "like",
                    Value = energy.Workshop
                });
            }

            // 添加产线名称查询条件（精确匹配）
            if (!string.IsNullOrEmpty(energy.ProductionLine))
            {
                filter.Conditions.Add(new FilterCondition
                {
                    Field = "ProductionLine",
                    Operator = "like",
                    Value = energy.ProductionLine
                });
            }

            // 添加物质类型查询条件（精确匹配）
            if (!string.IsNullOrEmpty(energy.Substance))
            {
                filter.Conditions.Add(new FilterCondition
                {
                    Field = "Substance",
                    Operator = "like",
                    Value = energy.Substance
                });
            }

            // 添加单位查询条件（精确匹配）
            if (!string.IsNullOrEmpty(energy.Unit))
            {
                filter.Conditions.Add(new FilterCondition
                {
                    Field = "Unit",
                    Operator = "=",
                    Value = energy.Unit
                });
            }

            // 添加能耗量范围查询
            if (energy.EnergyConsumption.HasValue)
            {
                filter.Conditions.Add(new FilterCondition
                {
                    Field = "EnergyConsumption",
                    Operator = ">=",
                    Value = energy.EnergyConsumption.Value
                });
            }
            // 始终添加未删除的条件
            filter.Conditions.Add(new FilterCondition
            {
                Field = "IsDeleted",
                Operator = "=",
                Value = false
            });
            // 添加时间范围查询
            if (!string.IsNullOrEmpty(energy.TimeCondition))
            {
                string[] dates = energy.TimeCondition.Split('至');
                DateTime startDate = DateTime.Parse(dates[0].Trim());
                DateTime endDate = DateTime.Parse(dates[1].Trim());
                filter.Conditions.Add(new FilterCondition
                {
                    Field = "CreateTime",
                    Operator = ">=",
                    Value = startDate
                });
                filter.Conditions.Add(new FilterCondition
                {
                    Field = "CreateTime",
                    Operator = "<=",
                    Value = endDate
                });


            }
        }
        /// <summary>
        /// 高级分页查询能源信息
        /// </summary>
        /// <param name="filter">分页过滤器</param>
        /// <param name="energy">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResult<Energy>> AdvancedPagedQueryAsync(QueryFilter filter, Energy energy)
        {
            Query(filter, energy);
            string groupByColumns = "";
            string TimegroupByColumns = "";
            if (energy.SelectedColumns.Length > 0)
            {
                foreach (var item in energy.SelectedColumns)
                {
                    TimegroupByColumns += item + ',';
                    groupByColumns += item + ',';
                }
            }
            //时间判断

            if (energy.TimeType == "year" || energy.TimeType == "yearrange")
            {
                TimegroupByColumns += "YEAR(CreateTime)as DateTimeType,";
                groupByColumns += "YEAR(CreateTime)";
            }
            if (energy.TimeType == "month" || energy.TimeType == "monthrange")
            {
                TimegroupByColumns += " FORMAT(CreateTime, 'yyyy-MM') as DateTimeType,";
                groupByColumns += "FORMAT(CreateTime, 'yyyy-MM')";
            }
            if (energy.TimeType == "date" || energy.TimeType == "daterange")
            {
                TimegroupByColumns += " FORMAT(CreateTime, 'yyyy-MM-dd') as DateTimeType,";
                groupByColumns += "FORMAT(CreateTime, 'yyyy-MM-dd')";
            }

            var conditions = new List<string>();
            var parameters = new DynamicParameters();

            string baseSql = $@"SELECT {TimegroupByColumns} SUM(EnergyConsumption) AS EnergyConsumption 
                   FROM EC_Energy 
                   WHERE 1=1";

            if (!string.IsNullOrEmpty(energy.DevName))
            {
                conditions.Add("DevName LIKE @DevName");
                parameters.Add("DevName", $"%{energy.DevName}%");
            }

            if (!string.IsNullOrEmpty(energy.FactoryName))
            {
                conditions.Add("FactoryName LIKE @FactoryName");
                parameters.Add("FactoryName", $"%{energy.FactoryName}%");
            }

            if (!string.IsNullOrEmpty(energy.Workshop))
            {
                conditions.Add("Workshop LIKE @Workshop");
                parameters.Add("Workshop", $"%{energy.Workshop}%");
            }

            if (!string.IsNullOrEmpty(energy.ProductionLine))
            {
                conditions.Add("ProductionLine LIKE @ProductionLine");
                parameters.Add("ProductionLine", $"%{energy.ProductionLine}%");
            }

            if (!string.IsNullOrEmpty(energy.Substance))
            {
                conditions.Add("Substance LIKE @Substance");
                parameters.Add("Substance", $"%{energy.Substance}%");
            }
            //时间范围
            if (!string.IsNullOrEmpty(energy.TimeCondition))
            {
                string[] dates = energy.TimeCondition.Split('至');
                DateTime startDate = DateTime.Parse(dates[0].Trim());
                DateTime endDate = DateTime.Parse(dates[1].Trim());

                conditions.Add("CreateTime >= @startDate and CreateTime<@endDate");
                parameters.Add("startDate", $"{startDate}");
                parameters.Add("endDate", $"{endDate}");
            }

            // 组合最终的 SQL
            string whereClause = conditions.Any() ? " AND " + string.Join(" AND ", conditions) : "";
            groupByColumns = $" GROUP BY {groupByColumns}";
            string sql = baseSql + whereClause + $"{groupByColumns}";

            //sql语句形式的分页查询
            var a = await _dapperRepository.QueryPagedAsync<Energy>(sql, parameters, filter.PageIndex, filter.PageSize, filter.OrderBy);

            return a;
        }

        /// <summary>
        /// 批量导入能源数据
        /// </summary>
        /// <param name="energies">能源数据列表</param>
        public async Task BatchImportAsync(IEnumerable<Energy> energies)
        {
            foreach (var energy in energies)
            {
                if (string.IsNullOrEmpty(energy.Id))
                {
                    energy.Id = Guid.NewGuid().ToString();
                }

                if (!energy.CreateTime.HasValue)
                {
                    energy.CreateTime = DateTime.Now;
                }

                await _repository.AddAsync(energy);
            }
        }
        #region 报表查询
        /// <summary>
        /// 年月日报表查询
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="energy"></param>
        /// <returns></returns>
        public async Task<PagedResult<Energy>> TimerPagedQuery(QueryFilter filter, Energy energy)
        {
            Query(filter, energy);
            return await _pagedRepository.GetPagedAsync(filter);
        }

        #endregion

        #region 看板信息
        /// <summary>
        /// 排名信息编写
        /// </summary>
        /// <returns></returns>
        public async Task<object> PaiMing()
        {
            //设备
            string sql = @"select DevName AS NAME,SUM(EnergyConsumption) EnergyConsumption from EC_Energy
GROUP BY DevName ";
            IEnumerable<device> device = await _dapperRepository.QueryAsync<device>(sql);
            //车间
            sql = @"select Workshop AS NAME,SUM(EnergyConsumption) EnergyConsumption from EC_Energy
GROUP BY Workshop";
            IEnumerable<workshop> workshop = await _dapperRepository.QueryAsync<workshop>(sql);
            //产线
            sql = @"select ProductionLine AS NAME,SUM(EnergyConsumption) EnergyConsumption from EC_Energy
GROUP BY ProductionLine";
            IEnumerable<productionLine> ProductionLine = await _dapperRepository.QueryAsync<productionLine>(sql);
            //物质
            sql = @"select Substance AS NAME,SUM(EnergyConsumption) EnergyConsumption from EC_Energy
GROUP BY Substance";
            IEnumerable<substance> substance = await _dapperRepository.QueryAsync<substance>(sql);
            var data = new { device, workshop, ProductionLine, substance };
            return data;
        }

        #endregion
    }
}